package com.hadoop.interceptor;

import com.hadoop.common.Constants;
import com.hadoop.dao.redis.RedisDao;
import com.hadoop.interceptor.util.HttpServletRequestUtils;
import com.hadoop.mybatis.po.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>检测用户登录的信息是否过期，如果过期需要重新登录。</p>
 *
 * @author Andy
 * @date 2017/10/12
 */
public class CheckUserLoginInterceptor implements HandlerInterceptor {
    @Resource
    private RedisDao redisDao;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //增加清除页面缓存
        response.setHeader( "Cache-Control", "no-cache,no-store");//HTTP 1.1
        response.setDateHeader( "Expires", 0 ); //prevent caching at the proxy server
        response.setHeader( "Pragma", "no-cache" );  //HTTP 1.0

        Cookie cookie = WebUtils.getCookie(request,Constants.COOKIE_KEY_WEB_HADOOP);
        if (null == cookie) {
            HttpServletRequestUtils.redirectUrl(request, response,"/web_hadoop/login", "未登录或超时退出");
            return false;
        }

        String key = Constants.LOGIN_USER_INFO + cookie.getValue();
        if (!redisDao.isKeyExist(key)) {
            HttpServletRequestUtils.redirectUrl(request, response,"/web_hadoop/login", "未登录或超时退出");
            return false;
        }

        User user = redisDao.readRedisVoFromHash(key, new User());
        if (null == user) {
            HttpServletRequestUtils.redirectUrl(request, response,"/web_hadoop/login", "未登录或超时退出");
            return false;
        }

        String invalidKey = Constants.INVALID_USER_ID + user.getId();
        if (redisDao.isKeyExist(invalidKey)) {
            HttpServletRequestUtils.redirectUrl(request, response,"/web_hadoop/login", "当前用户已被锁定，请管理员联系。");
            return false;
        }

        request.getSession().setAttribute("user",user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, Exception e) throws Exception {

    }
}
